<template>
    <div class="erpInfoBaseAccount-container flex flex-col">
        <a-card class="mb-2.5">
            <common-form :model="state.queryForm" name="account-form" @query="handleQuery" @add="handleAdd"
                @reset="handleReset">
                <a-form-item label="账户名称" name="name" class="w-1/2.5">
                    <a-input v-model:value="state.queryForm.name" />
                </a-form-item>
                <a-form-item label="编号" name="serialNo" class="w-1/2.5">
                    <a-input v-model:value="state.queryForm.serialNo" />
                </a-form-item>
            </common-form>
        </a-card>
        <a-card class="flex-1 card-table">
            <common-table :columns="columns" :data="state.tableData" :pagination="{
                total: state.tableParams.total,
                current: state.tableParams.page,
                pageSize: state.tableParams.pageSize,
                showQuickJumper: true,
                showSizeChanger: true,
                pageSizeOptions: ['2', '5', '10', '20'],
                showTotal: (total: number) => `总数: ${total}`
            }" :loading="state.loading" @change="changePagination">
                <template #bodyCell="{ column, text, record }">
                    <template v-if="column.dataIndex === 'operation'">
                        <div class="w-full">
                            <a-button ghost type="primary" class="mr-1" @click="handleEdit(record)">编辑</a-button>
                            <a-button danger type="primary" class="mr-1" @click="handleDelete(record)">删除</a-button>
                        </div>
                    </template>
                    <template v-else-if="column.dataIndex == 'enable'">
                        <a-tag v-if="record.enable" color="green">启用</a-tag>
                        <a-tag v-else color="red">停用</a-tag>
                    </template>
                    <template v-else-if="column.dataIndex == 'isDefault'">
                        <a-switch
                            v-model:checked="record.isDefault"
                            checked-children="是"
                            un-checked-children="否"
                            size="small"
                            @change="handleAccountDefaut(record)"
                        />
                    </template>
                    <template v-else-if="column.dataIndex == 'initialAmount' || column.dataIndex == 'currentAmount'">
                        <span>{{ formatCurrency(record[column.dataIndex]) }}</span>
                    </template>
                </template>
            </common-table>
        </a-card>
        <a-modal v-model:open="state.isShow" :title="state.isEdit ? '编辑账户' : '新增账户'" @ok="handleAddEdit"
            @cancel="handleCancel">
            <a-form ref="formRef" :model="state.formState" name="account-form" autocomplete="off"
                :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
                <a-form-item label="账户名称" name="name" :rules="[{ required: true, message: '账户名称不能为空', trigger: 'blur' }]">
                    <a-input v-model:value="state.formState.name" placeholder="请输入账户名称" />
                </a-form-item>
                <a-form-item label="编号" name="serialNo" :rules="[{ required: true, message: '编号不能为空', trigger: 'blur' }]">
                    <a-input v-model:value="state.formState.serialNo" placeholder="请输入编号" />
                </a-form-item>
                <a-form-item label="期初金额" name="initialAmount" :rules="[{ required: true, message: '期初金额不能为空', trigger: 'blur' }]">
                    <a-input-number class="w-full" :min="0" :precision="2" v-model:value="state.formState.initialAmount" placeholder="请输入期初金额" />
                </a-form-item>
                <a-form-item label="备注" name="remark">
                    <a-input v-model:value="state.formState.remark" placeholder="请输入备注" />
                </a-form-item>
                <a-form-item label="排序" name="sort">
                    <a-input-number class="w-full" :min="0" v-model:value="state.formState.sort" />
                </a-form-item>
                <a-form-item label="状态" name="enable">
                    <a-switch v-model:checked="state.formState.enable" />
                </a-form-item>
                <a-form-item label="是否默认" name="isDefault">
                    <a-switch v-model:checked="state.formState.isDefault" @change="handleAccountAddEditisDefaultChange"/>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script setup lang="ts" name="ErpInfoBaseAccount">
import { ref, reactive, onMounted } from 'vue'
import CommonForm from '@/components/common-form/index.vue'
import CommonTable from '@/components/common-table/index.vue'
import { getInfoBaseAccountListApi, addInfoBaseAccountApi, deleteInfoBaseAccountApi, updateInfoBaseAccountApi, updateAccountDefaultApi } from '@/api/erp/infobase'
import type { ResType } from '@/api/types'
import type { TableParamsResType } from '@/views/system/onlineUser/type'
import type { FormInstance } from 'ant-design-vue'
import { showMsg } from '@/utils'

defineOptions({
    name: "ErpInfoBaseAccount"
})

const formRef = ref<FormInstance>()

const state = reactive({
    queryForm: {
        name: "",
        serialNo: ""
    } as any,
    tableData: [] as any[],
    tableParams: {
        page: 1,
        pageSize: 50,
        total: 0 as any,
    },
    formState: {
        enable: true,
        sort: 0,
        isDefault: false
    } as any,
    loading: false,
    isShow: false,
    isEdit: false
})

const columns: any[] = [
    {
        title: '序号',
        align: "center",
        width: 60,
        customRender: ({ index }: { index: number }) => {
            return `${index + 1}`;
        },
        fixed: 'left',
    },
    {
        title: '账户名称',
        align: "center",
        key: "name",
        dataIndex: 'name',
        width: 150,
    },
    {
        title: '编号',
        align: "center",
        key: "serialNo",
        dataIndex: 'serialNo',
        width: 150,
    },
    {
        title: '期初金额',
        align: "center",
        key: "initialAmount",
        dataIndex: 'initialAmount',
        width: 150,
    },
    {
        title: '当前余额',
        align: "center",
        key: "currentAmount",
        dataIndex: 'currentAmount',
        width: 150,
    },
    {
        title: '备注',
        align: "center",
        key: "remark",
        dataIndex: 'remark',
        width: 200,
    },
    {
        title: '状态',
        align: "center",
        key: "enable",
        dataIndex: 'enable',
        width: 100,
    },
    {
        title: '是否默认',
        align: "center",
        key: "isDefault",
        dataIndex: 'isDefault',
        width: 100,
    },
    {
        title: '操作',
        align: 'center',
        key: "operation",
        dataIndex: 'operation',
        width: 250,
        fixed: 'right',
    }
]

// 格式化金额显示
const formatCurrency = (value: number): string => {
    if (value === null || value === undefined) return '0.00';
    return value.toFixed(2);
}

const handleQuery = async () => {
    state.loading = true
    const params = Object.assign(state.tableParams, state.queryForm)
    try {
        const res: ResType<TableParamsResType<any>> = await getInfoBaseAccountListApi(params)
        state.tableData = res.data.result.items
        state.tableParams.total = res.data.result.total
    } catch (error) {
        showMsg('查询失败', 'error')
    } finally {
        state.loading = false
    }
}

const handleAdd = () => {
    // 重置表单状态
    formRef.value?.resetFields()
    state.formState = {
    }
    state.isShow = true
    state.isEdit = false
}

const handleReset = () => {
    state.queryForm = {
        name: "",
        serialNo: ""
    }
    handleQuery()
}

const handleAddEdit = async () => {
    await formRef.value?.validate()
    try {
        let res: ResType<any>
        if (state.isEdit && state.formState.id) {
            res = await updateInfoBaseAccountApi(state.formState)
            if (res.data.code == 200) {
                showMsg("编辑成功", 'success')
            }
        } else {
            res = await addInfoBaseAccountApi(state.formState)
            if (res.data.code == 200) {
                showMsg("添加成功", 'success')
            }
        }
        if (res?.data.code == 200) {
            handleCancel()
            await handleQuery()
        }
    } catch (error) {
        showMsg('操作失败', 'error')
    }
}

const handleCancel = () => {
    state.isShow = false
    state.formState = {
        enable: true,
        sort: 0,
        isDefault: false
    }
    formRef.value?.resetFields()
}

const changePagination = async (pagination: { current: number, pageSize: number }) => {
    state.tableParams.page = pagination.current
    state.tableParams.pageSize = pagination.pageSize
    await handleQuery()
}

const handleEdit = (record: any) => {
    state.formState = { ...record }
    state.isShow = true
    state.isEdit = true
}

const handleDelete = async (record: any) => {
    try {
        const res: ResType<any> = await deleteInfoBaseAccountApi({ id: record.id })
        if (res.data.code == 200) {
            showMsg("删除成功", 'success')
            await handleQuery()
        } else {
            showMsg("删除失败", 'error')
        }
    } catch (error) {
        showMsg('删除失败', 'error')
    }
}

const handleAccountDefaut = async (val:any)=>{
    const res:ResType<any> = await updateAccountDefaultApi({id:val.id})
    if(res.data.code == 200){
        showMsg("设置成功", 'success')
        await handleQuery()
    } else {
        showMsg("设置失败", 'error')
    }
}

const handleAccountAddEditisDefaultChange = (v:any)=>{
    // 账户默认启用必须是启用状态
    if(v && !state.formState.enable){
        showMsg("账户默认启用必须是启用状态", 'success')
        state.formState.enable = true
    }
}

onMounted(async () => {
    await handleQuery()
})
</script>

<style lang="scss" scoped>
.erpInfoBaseAccount-container {
    .card-table {
        :deep(.ant-card-body) {
            height: 100%;
        }
    }
}

:deep(.ant-table-cell-fix-right) {
    // right: 0 !important;
}

:deep(.ant-btn >span) {
    display: inline-flex !important;
}
</style>